package org.standard.base.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;

import org.standard.base.model.BaseDept;
import org.standard.base.model.BaseRole;
import org.standard.base.model.BaseUser;
import org.standard.base.service.BaseDeptService;
import org.standard.commons.utils.DAO;
import org.standard.sys.model.SysLog;

public class BaseDeptServiceImpl implements BaseDeptService {
	
	private DAO dao;
	private static final char SUCCESS = '1';
	private static final char FAIL = '0';
	private static final String DEPARTPARENT = "0";

	public DAO getDao() {
		return dao;
	}

	public void setDao(DAO dao) {
		this.dao = dao;
	}

	@Override
	public char createDepart(BaseDept department) {
		// TODO Auto-generated method stub
		if(isDeptIn(department) == true){
			String departId = (String)dao.save(department);
			return SUCCESS;
		}else{
			return FAIL;
		}
	}

	/**
	 * 判断部门是否添加过
	 * @param department
	 * @return
	 */
	private boolean isDeptIn(BaseDept depart){
		boolean s = false;
		String hql = "";
		if(StringUtils.isNotBlank(depart.getDeptId())){
			hql = "from BaseDept where deptName = '"+depart.getDeptName()+"' and deptId != '"+depart.getDeptId()+"'";
		}else{
			hql = "from BaseDept where deptName = '"+depart.getDeptName()+"'";
		}
		List list = dao.find(hql);
		
		if(list.size() == 0){
			s = true;
		}
		
		return s;
	}
	
	@Override
	public char updateDept(BaseDept department) {
		// TODO Auto-generated method stub
		if(isDeptIn(department) == true){
			String hql="update BaseDept set deptName='"+department.getDeptName()+"'," +
					"deptOrder='"+department.getDeptOrder()+"',deptTel='"+department.getDeptTel()+"'," +
					"deptFax='"+department.getDeptFax()+"',deptParent='"+department.getDeptParent()+"'," +
					"deptManager='"+department.getDeptManager()+"',deptLeader1='"+department.getDeptLeader1()+"'," +
					"deptLeader2='"+department.getDeptLeader2()+"',deptFunc='"+department.getDeptFunc()+"' " +
					" where deptId='"+department.getDeptId()+"'";
			dao.updateBulk(hql);
			return SUCCESS;
		}else{
			return FAIL;
		}
	}
	
	
	@Override
	public List<BaseDept> searchAllDepart() {
		// TODO Auto-generated method stub
		String hql = "from BaseDept where 1=1 order by deptOrder";
		List list = dao.find(hql);
		if(list.size() > 0 ){
			return list;
		}else{
			
			return new ArrayList();
		}
	}

	@Override
	public BaseDept searchByDepartId(String departId) {
		// TODO Auto-generated method stub
		BaseDept department = (BaseDept)dao.find(BaseDept.class, departId);
		
		String deptManager = department.getDeptManager();
		
		if(StringUtils.isNotBlank(deptManager)){
			deptManager = deptManager.substring(0, deptManager.lastIndexOf(","));
			String deptManagerName = "";
			
			if(deptManager.indexOf(",")!= -1){
				String[] users = deptManager.split(",");
				for(int i=0;i<users.length;i++){
					BaseUser user = (BaseUser)dao.find(BaseUser.class, users[i]);
					deptManagerName += user.getUserName()+",";
				}
			}else{
				BaseUser user = (BaseUser)dao.find(BaseUser.class, deptManager);
				deptManagerName += user.getUserName()+",";
			}
			
			department.setDeptManagerName(deptManagerName);
		}
		
		
		String deptLeader1 = department.getDeptLeader1();
		if(StringUtils.isNotBlank(deptLeader1)){
			deptLeader1 = deptLeader1.substring(0, deptLeader1.lastIndexOf(","));
			String deptLeader1Name = "";
			
			if(deptLeader1.indexOf(",")!= -1){
				String[] users = deptLeader1.split(",");
				for(int i=0;i<users.length;i++){
					BaseUser user = (BaseUser)dao.find(BaseUser.class, users[i]);
					deptLeader1Name += user.getUserName()+",";
				}
			}else{
				BaseUser user = (BaseUser)dao.find(BaseUser.class, deptLeader1);
				deptLeader1Name += user.getUserName()+",";
			}
			
			department.setDeptLeader1Name(deptLeader1Name);
		}
		
		String deptLeader2 = department.getDeptLeader2();
		if(StringUtils.isNotBlank(deptLeader2)){
			deptLeader2 = deptLeader2.substring(0, deptLeader2.lastIndexOf(","));
			String deptLeader2Name = "";
			
			if(deptLeader2.indexOf(",")!= -1){
				String[] users = deptLeader2.split(",");
				for(int i=0;i<users.length;i++){
					BaseUser user = (BaseUser)dao.find(BaseUser.class, users[i]);
					deptLeader2Name += user.getUserName()+",";
				}
			}else{
				BaseUser user = (BaseUser)dao.find(BaseUser.class, deptLeader2);
				deptLeader2Name += user.getUserName()+",";
			}
			
			department.setDeptLeader2Name(deptLeader2Name);
		}
		
		if(department != null){
			return department;
		}else{
			return new BaseDept();
		}
		
	}

	@Override
	public List<BaseDept> searchChildDepart(String parentDeptId) {
		// TODO Auto-generated method stub
		String hql = "from BaseDept where deptParent = '"+parentDeptId+"' order by deptOrder";
		
		return   dao.find(hql);
	}

	@Override
	public String departTree(String parentId,HttpServletRequest request) {
		// TODO Auto-generated method stub
		List<BaseDept> list = dao.find("from BaseDept where deptParent = '"+parentId+"' order by deptOrder");
		if (list != null && list.size() > 0) {
			//CTX
			String ctx = request.getContextPath();
			StringBuffer responseXML = new StringBuffer("<?xml version='1.0' encoding='UTF-8'?><tree>");
			//循环一级节点
			for (BaseDept department : list) {
				responseXML.append("<tree");
				//节点名称
				responseXML.append(" text='" + department.getDeptName()+ "'");
				//节点超链接
				responseXML.append(" src='" + ctx+ "/depart/depart_departTree.action?department.deptParent="	+ department.getDeptId()+"'");
				//节点超链接
				responseXML.append(" action='" + ctx+ "/depart/depart_managerDept.action?department.deptId="	+ department.getDeptId() + "'");
				//节点超链接目标
				responseXML.append(" target='mright'");
				//节点图片
				responseXML.append(" icon='" + ctx + "/images/main/depart.gif'");
				//节点打开图片
				responseXML.append(" openIcon='" + ctx + "/images/main/depart.gif'");
				//节点
				responseXML.append("/>");
			}
			responseXML.append("</tree>");
			
			return responseXML.toString();
		} else {
			return "<?xml version='1.0' encoding='UTF-8'?><tree></tree>";
		}
	}

	@Override
	public List<BaseDept> departSelect() {
		// TODO Auto-generated method stub
		List<BaseDept> selectList = new ArrayList<BaseDept>();
		
		String hql = "from BaseDept where deptParent = '"+DEPARTPARENT+"' order by deptOrder";
		List<BaseDept> list =  new ArrayList(dao.find(hql));
		for(BaseDept depart:list){
			depart.setDeptNames(depart.getDeptName());
			selectList.add(depart);
			selectList.addAll(getChildDeparts(depart.getDeptId(),1));
		}
		return selectList;
	}

	private List<BaseDept> getChildDeparts(String parentId,final int count){
		List<BaseDept> list1 = new ArrayList<BaseDept>();
		List<BaseDept> list = new ArrayList<BaseDept>(searchChildDepart(parentId));
		String s2 = "";
		for(int i=0;i<count;i++){
			s2 += "&nbsp;&nbsp;&nbsp;";
		}
		for(BaseDept depart:list){
			depart.setDeptNames(s2+depart.getDeptName());
			list1.add(depart);
			List<BaseDept> list2 = getChildDeparts(depart.getDeptId(),count+1);
			list1.addAll(list2);
		}
		return list1;
	}

	@Override
	public char deleteDepart(BaseDept department) {
		// TODO Auto-generated method stub
		String hql1 = "from BaseUser where deptId = '"+department.getDeptId()+"' or deptIdOther like '%"+department.getDeptId()+"%'";
		
		List<BaseUser> users = dao.find(hql1);
		
		List<BaseDept> departmnet = searchChildDepart(department.getDeptId());
		
		if(users.size()==0 && departmnet.size()==0){
			
			dao.delete(department);
			return SUCCESS;
		}else{
			
			return FAIL;
		}
	}

	@Override
	public void createLog(BaseUser admin, String ip, String message, String code) {
		// TODO Auto-generated method stub
		dao.createLog(new  SysLog(admin.getUserId(),ip, code, message));
	}

	@Override
	public List<BaseDept> findAllByNode() {
		// TODO Auto-generated method stub
		String hql="from BaseDept a where not exists(select b from BaseDept b where a.deptId=b.deptParent)";
		return dao.find(hql);
	}
	
}
